package cn.com.bsoft.wePortal.partner.service

import cn.com.bsoft.kotlinEx.AllOpen
import cn.com.bsoft.kotlinEx.StatusAndMessageError
import cn.com.bsoft.kotlinEx.logger
import cn.com.bsoft.kotlinEx.randomString
import cn.com.bsoft.wePortal.partner.dao.PartnerDao
import cn.com.bsoft.wePortal.partner.dto.UpdatePartnerReq
import cn.com.bsoft.wePortal.partner.entity.Partner
import cn.com.bsoft.wePortal.partner.model.PartnerProperties
import org.springframework.beans.factory.annotation.Autowired
import javax.annotation.PostConstruct

interface PartnerService{
    fun allPartner():List<Partner>
    fun createPartner(code:String,title:String):Partner
    fun setupPartner(code:String,title:String):Partner
    fun query(code:String):Partner?
    fun update(req: UpdatePartnerReq):Partner
}

@AllOpen
class DefaultPartnerService:PartnerService{

    @Autowired
    lateinit var partnerDao:PartnerDao

    @Autowired
    lateinit var partnerProperties:PartnerProperties

    @PostConstruct
    fun setup(){
        setupPartner(partnerProperties.keyDemo,partnerProperties.keyDemo)
    }

    override fun allPartner(): List<Partner> {
        return partnerDao.findAll()
    }

    override fun createPartner(code: String, title: String): Partner {
        var partner = Partner(code)
        partner.title = title

        partner.secret = randomString(20)
        if (code == partnerProperties.keyDemo)
            partner.secret = partnerProperties.demoSecret

        logger.info("create partner:$code secret:${partner.secret}")
        return partnerDao.saveAndFlush(partner)
    }

    override fun setupPartner(code: String, title: String): Partner {
        var partner = query(code)?:createPartner(code,title)

        return partner
    }

    override fun query(code: String): Partner? {
        return partnerDao.findById(code).orElse(null)
    }

    override fun update(req: UpdatePartnerReq): Partner {
        var partner = query(req.code?:"") ?: throw StatusAndMessageError("partner:${req.code}不存在")

        partner.title = req.title ?: partner.title
        partner.enabled = req.enable ?: partner.enabled
        partner.phone = req.phone ?: partner.phone
        partner.mail = req.mailBox ?: partner.mail

        return partnerDao.saveAndFlush(partner)
    }

}